import { postUserData, postProductData, postQueryBySysDictNos, getQueryOrgTree } from '@/api/common'
import { CONSTANT_OBJ } from '@/utils/constant'
// 公共模块小仓库
const state = {

  loginUser:{},
  // 用户账户
  users: {},
  // 产品
  products: [],
  dicts: {},
  orgTree: [],
  permissionTree: []
}

const mutations = {
  QUERY_USER_DATA (state, users) {
    state.users = users || {}
  },
  GET_PRODUCT_DATA (state, products) {
    state.products = products || []
  },
  GET_DICTS (state, dicts) {
    state.dicts = dicts || {}
  },
  GET_ORG_TREE (state, orgTree) {
    state.orgTree = orgTree || []
  },
  GET_PERMISSION_TREE (state, permissionTree) {
    state.permissionTree = permissionTree || []
  },
  GET_LOGIN_USER (state, loginUser) {
    state.loginUser = loginUser || {}
  }
}

const actions = {
  // 获取用户
  async queryUserData ({ commit }, data) {
    let result = await postUserData(data)
    const { responseCode } = result
    if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
      commit('QUERY_USER_DATA', result.data)
    }
  },
  async queryProductData ({ commit }, data) {
    let result = await postProductData(data)
    const { responseCode } = result
    if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
      commit('GET_PRODUCT_DATA', result.data.list)
    }
  },
  async queryBySysDictNos ({ commit }, data) {
    let result = await postQueryBySysDictNos(data)
    const { responseCode } = result
    if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
      const dicts = {}
      result.data.forEach(v => {
        const childMap = {}
        if (v.childList) {
          v.childList.forEach(u => {
            childMap[u.dictNo] = u.dictName
          })
        }
        v.childMap = childMap
        dicts[v.dictNo] = v
      })
      commit('GET_DICTS', dicts)
    }
  },
  async queryOrgTree ({ commit }) {
    let result = await getQueryOrgTree()
    const { responseCode, data } = result
    if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
      commit('GET_ORG_TREE', data)
    }
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
